package main.java.DMDE.persistence;

import java.util.UUID;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import main.java.DMDE.model.Diagram;
import main.java.DMDE.model.Entity;
import main.java.DMDE.model.relationships.FactoryRelationship;
import main.java.DMDE.model.relationships.Relationship;
import main.java.DMDE.model.relationships.RelationshipComponent;
import main.java.common.IXmlManager;

public class RelationshipXmlManager implements IXmlManager<Relationship> {

	private RelationshipComponentXmlManager relationshipComponentManager = new RelationshipComponentXmlManager();
	public Diagram currentDiagram = null;
	
	
	public Element getElementFromItem(Relationship parameter, Document document) {
		Element relationshipElement = document.createElement("relationship");
		relationshipElement.setAttribute("linkName", parameter.getLinkName().toString());
		relationshipElement.setAttribute("id", parameter.getId().toString());
		relationshipElement.setAttribute("type", parameter.getType().toString());
		Element elementA = document.createElement("elementA");
		elementA.appendChild(relationshipComponentManager.getElementFromItem(parameter.getComponentA(), document));
		relationshipElement.appendChild(elementA);
		Element elementB = document.createElement("elementB");
		elementB.appendChild(relationshipComponentManager.getElementFromItem(parameter.getComponentB(), document));
		relationshipElement.appendChild(elementB);
		return relationshipElement;
	}

	@Override
	public Relationship getItemFromXmlElement(Element element) throws Exception {
		Relationship relationship = FactoryRelationship.createEmpty(element.getAttribute("type"), currentDiagram);
		relationship.setId(UUID.fromString(element.getAttribute("id")));
		Element a = (Element) element.getElementsByTagName("elementA").item(0).getChildNodes().item(0);
		RelationshipComponentProxy proxyA = (RelationshipComponentProxy) relationshipComponentManager.getItemFromXmlElement(a);
		relationship.setComponentA(fromProxy(proxyA, currentDiagram.getEntityById(proxyA.id)));
		Element b = (Element) element.getElementsByTagName("elementB").item(0).getChildNodes().item(0);
		RelationshipComponentProxy proxyB = (RelationshipComponentProxy) relationshipComponentManager.getItemFromXmlElement(b);
		relationship.setComponentB(fromProxy(proxyB, currentDiagram.getEntityById(proxyB.id)));				
		return relationship;
	}

	private RelationshipComponent fromProxy(RelationshipComponentProxy proxy,
			Entity entity) {
		RelationshipComponent c = new RelationshipComponent();
		c.setMaxCardinality(proxy.maxCardinality);
		c.setMinCardinality(proxy.minCardinality);
		c.setEntity(entity);
		return c;
	}
}
